import { defineStore } from "pinia"
import { computed, ref } from "vue"
import { useUserStore } from "./user"
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart"

export const useCartStore = defineStore("cart", () => {

  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)

  const cartList = ref([])

  // 获取最新购物车列表
  const updateNewList = async () => {
    const res = await findNewCartListAPI()
    cartList.value = res.result
  }

  // 添加购物车商品
  const addCart = async (goods) => {
    const { skuId, count } = goods
    if(isLogin) {
      // 已登录
      await insertCartAPI({ skuId, count })
      updateNewList()
    } else {
      // 未登录
      // 已添加过 count + 1
      // 未添加过 直接push
      const item = cartList.value.find(item => goods.skuId === item.skuId)
      if(item) {
        item.count++
      } else {
        cartList.value.push(goods)
      }
    }
  }

  // 删除购物车商品
  const delCart = async (skuId) => {
    if(isLogin) {
      await delCartAPI([skuId])
      updateNewList()
    } else {
      cartList.value = cartList.value.filter(item => item.skuId !== skuId)
    }
  }

  // 清空购物车
  const clearCart = () => {
    cartList.value = []
  }


  // 单选
  const singleCheck = (skuId, selected) => {
    const item = cartList.value.find(item => item.skuId === skuId)
    item.selected = selected
  }
  // 全选
  const allCheck = (selected) => {
    cartList.value.forEach(item => item.selected = selected)
  }

  // 计算属性
  // 总数
  const allCount = computed(() => {
    return cartList.value.reduce((pre, cur) => pre + cur.count, 0)
  })
  // 总价
  const allPrice = computed(() => {
    return cartList.value.reduce((pre, cur) => pre + cur.count * cur.price, 0)
  })
  // 已选数量
  const selectedCount = computed(() => {
    return cartList.value.filter(item => item.selected).reduce((pre, cur) => pre + cur.count, 0)
  })
  // 已选商品价格合计
  const selectedPrice = computed(() => {
    return cartList.value.filter(item => item.selected).reduce((pre, cur) => pre + cur.count * cur.price, 0)
  })
  // 是否全选
  const isAll = computed(() => {
    return cartList.value.every(item => item.selected)
  })

  return {
    cartList,
    allCount,
    allPrice,
    isAll,
    selectedCount,
    selectedPrice,
    addCart,
    delCart,
    singleCheck,
    allCheck,
    clearCart,
    updateNewList
  }
}, {
  persist: true,
})